/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

class ClassDirectory implements Code {
	private final FileReader fileReader = new FileReader();

	private final String directory;

	public ClassDirectory(String directory) {
		this.directory = directory;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Code methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	public byte[] findClass(String className) {
		return containsClass(className) ? fileReader.readContents(classFile(className)) : null;
	}

	public InputStream openFile(String fileName) throws FileNotFoundException {
		return new FileInputStream(directory + File.separator + fileName);
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Object methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public String toString() {
		return "ClassDirectory: " + directory;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation
	///////////////////////////////////////////////////////////////////////////////////////////////

	private boolean containsClass(String className) {
		return classFile(className).exists();
	}

	private File classFile(String className) {
		return new File(directory + File.separator + className.replace('.', File.separatorChar) +
			".class");
	}
}
